package com.venutech.gongan.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.shihang.misc.date.DateTimeUtil;
import com.venutech.gongan.common.BusinessException;
import com.venutech.gongan.common.Constants;
import com.venutech.gongan.entity.*;
import com.venutech.gongan.model.ResultFormat;
import com.venutech.gongan.service.*;
import com.venutech.gongan.util.MD5Util;
import com.venutech.gongan.util.QRCodeUtil;
import com.venutech.gongan.util.ResultUtil;
import com.venutech.gongan.vo.JkgwAddOptionVO;
import com.venutech.gongan.vo.JkgwVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;
import java.util.concurrent.ExecutorService;

/**
 * 监控杆位控制器
 */
@RestController
@RequestMapping("jkgw")
@Api(tags = {"监控杆位控制层接口"})
@Slf4j
public class JkgwController extends AbstractControllerBase {

    @Value("${qrcode.external-domain}")

    String qrCodeExternalDomain;
    @Value("${qrcode.save-dir}")
    String qrCodeSaveDir;

    @Value("${qrcode.path-mapping}")
    String qrCodePathMapping;

    @Autowired
    private ResourceLoader resourceLoader;
    @Resource
    private DictDataService dictDataService;
    @Resource
    private JkgwService jkgwService;
    @Resource
    private QRCodeService qrCodeService;
    @Resource
    private RzLogService rzLogService;
    @Resource
    private QdsxjService qdsxjService;
    @Resource
    private EquipmenService equipmenService;

    @Autowired
    private AuditLogService auditLogService;


    //规定两个经纬度距离差0.01千米，即杆位距离限制为10米
    @Value("${gps.limitedDistance:0.01}")
    private double limitedDistance;

    @Value("${RZLOG_XTID}")
    String xtid;


    @ApiOperation("查询监控杆位列表")
    @GetMapping("/list")
    @ResponseBody
    public Map<String, Object> jkgw_list(@RequestParam Integer page, @RequestParam Integer limit,
                                         @RequestParam(required = false) String begintime,
                                         @RequestParam(required = false) String endtime,
                                         @RequestParam(required = false) String badw,
                                         @RequestParam(required = false) String gw_name,
                                         @RequestParam(required = false,defaultValue = "0") Integer type) {
        log.info("gw_name杆位名称:  "+gw_name);
        Map<String, Object> result = new HashMap<>();
        Page<Jkgw> p = jkgwService.getInfo(page,limit,begintime,endtime,badw,gw_name);
        result.put("code","0");
        result.put("count",p.getTotal());
        result.put("data",p.getRecords());
        if(type==1){
            String message=String.format("监控杆位查询:监控杆位名称:%s",gw_name);
            String opCondition = String.format("工单查询:工单名称:%s",gw_name);
            asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_QUERY, Constants.LOG_OK, opCondition, message);
        }else{
            result.put("msg", "监控杆位查询成功");
        }
        return result;
    }

    @ApiOperation("添加监控杆位的选项列表")
    @GetMapping("options")
    public JkgwAddOptionVO options() {
        List<QRCode> qrCodeList=qrCodeService.getQrBm();
        int eightSeq = qrCodeService.getEightSeq();
        //区域编码
        List<DictData> list = dictDataService.getSelQybm();
        List<DictData> listqybm = new ArrayList<>();
        for (DictData data:list) {
            if (!data.getDict_label().equals("姑苏区")){
                listqybm.add(data);
            }
        }
        //小类编码
        List<DictData> listxlbm = dictDataService.getSelXlbm();

        Log log=new Log();
        log.setCzlx(Constants.VIEW);

        String message=String.format("添加监控杆件页面跳转");
        String opCondition = String.format("工单查询:工单名称:%s");
        asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_QUERY, Constants.VIEW, opCondition, message);

        return new JkgwAddOptionVO(qrCodeList, eightSeq, listqybm, listxlbm);
    }

    /**
     * 添加监控杆位
     * @return
     */
    @ApiOperation("添加监控杆位")
    @PostMapping("save")
    @ResponseBody
    public ResultFormat jkgwSave(@RequestParam(name = "gw_name",required = true) String gw_name,
                                 @RequestParam(name = "gw_wz",required = true) String gw_wz,
                                 @RequestParam(name = "gw_bw",required = true) String gw_bw,
                                 @RequestParam(name = "gw_jd",required = true) Double gw_jd,
                                 @RequestParam(name = "gw_wd",required = true) Double gw_wd,
                                 @RequestParam(name = "gw_zx",required = true) String gw_zx,
                                 @RequestParam(name = "qybm",required = false)String qybm,
                                 @RequestParam(name = "xlxbm",required = false)String xlxbm,
                                 @RequestParam(name = "xh",required = false)String xh,
                                 HttpServletResponse response){
        Log log1=new Log();
        String qrIdMD5=null;
        String qr_bm=null;
        log.info("qybm:   "+qybm+"  xlxbm；  "+xlxbm+"  xh:   "+xh+"===========================");
        //二维码生成
        try {
            log.info("最大序列："+qrCodeService.getLastSeq());
            int qr_id=0;
            if(qrCodeService.getLastSeq()==null){
                qr_id=1;
            }else {
                qr_id = qrCodeService.getLastSeq() + 1;
            }
            qrIdMD5 = MD5Util.MD5Encode(String.valueOf(qr_id), "UTF-8");
            String codeContent=String.format("%s?qr_id=%s", qrCodeExternalDomain, qrIdMD5);

            log.info("二维码codeContent："+codeContent);
            //二维码物理保存地址
            File codeImgFileSaveDir = new File(qrCodeSaveDir);
            //文件名称
            String fileName = qr_id +".png";

            org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:static/qrcodebg.png");
            if(!resource.exists()) {
                throw new BusinessException(String.format("gbImgfile not exists [%s]", resource.getURL()));
            }
            int length = (int)resource.contentLength();
            byte[] fileData = new byte[length];
            resource.getInputStream().read(fileData);


            qr_bm=qybm+"-"+xlxbm+"-"+xh;
            //二维码对象
            QRCode qrCode = new QRCode();
            qrCode.setQr_id(qr_id);
            qrCode.setQr_codeContent(codeContent);
            qrCode.setQr_codeImgFileSaveDir(fileName);   // 此处只保存文件名称，不带路径，路径配置化
            qrCode.setQybm(qybm);
            qrCode.setXlxbm(xlxbm);
            qrCode.setXh(xh);
            qrCode.setQr_bm(qr_bm);
            qrCode.setQrid_md5(qrIdMD5);

            // 调用工具类生成二维码并输出到输出流中
            QRCodeUtil.createCodeToFile(codeContent,codeImgFileSaveDir,fileName,fileData,120,250);
            //插入数据库
            int i = qrCodeService.insert(qrCode);

            log.info("成功生成二维码!");
        } catch (Exception e) {
            log.error("发生错误， 错误信息是：{}！", e);
        }

        //监控杆件
        Jkgw jkgw = new Jkgw();
        jkgw.setGw_name(gw_name);
        jkgw.setGw_wz(gw_wz);
        jkgw.setGw_bw(gw_bw);
        jkgw.setGw_jd(gw_jd);
        jkgw.setGw_wd(gw_wd);
        jkgw.setGw_zx(gw_zx);
        jkgw.setGw_bm(qr_bm);
        jkgw.setQrid_md5(qrIdMD5);
        //插入半径默认值
        jkgw.setGw_search_radius(Constants.COMMON_RADIUS);

        int gw_id = jkgwService.insert(jkgw);

        String message = String.format("添加杆件：　杆件id=%d, 杆件名称=%s", jkgw.getGw_id(), jkgw.getGw_name());
        String opCondition = String.format("gw_id=%d", gw_id);
        asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_ADD, Constants.INSERT, opCondition, message);

        return ResultUtil.success();
    }

    @DeleteMapping("/{id}}")
    @ResponseBody
    public Integer jkgwDelete(@PathVariable("id") Integer gw_id) {
        jkgwService.deleteById(gw_id);

        Jkgw jkgw = jkgwService.getById(gw_id);
        String message = String.format("删除杆件：　杆件Id=%d, 杆件名称=%s", jkgw.getGw_id(), jkgw.getGw_name());
        String opCondition = String.format("gw_id=%d", gw_id);

        asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_DELETE, Constants.DELETE, opCondition, message);

        return 0;
    }

    @PostMapping(value = "update/{id}")
    @ResponseBody
    public void jkgwUpdate(@PathVariable("id") String gw_id,
                          @RequestParam(name = "gw_name",required = true) String gw_name,
                          @RequestParam(name = "gw_wz",required = true) String gw_wz,
                          @RequestParam(name = "gw_bw",required = true) String gw_bw,
                          @RequestParam(name = "gw_jd",required = true) Double gw_jd,
                          @RequestParam(name = "gw_wd",required = true) Double gw_wd,
                          @RequestParam(name = "gw_zx",required = true) String gw_zx,
                           @RequestParam(name = "gw_bm",required = true) String gw_bm){
        RzLog rzLog = new RzLog();

        Jkgw jkgw = new Jkgw();
        jkgw.setGw_id(Integer.parseInt(gw_id));
        jkgw.setGw_name(gw_name);
        jkgw.setGw_wz(gw_wz);
        jkgw.setGw_bw(gw_bw);
        jkgw.setGw_jd(gw_jd);
        jkgw.setGw_wd(gw_wd);
        jkgw.setGw_zx(gw_zx);
        jkgw.setGw_bm(gw_bm);

        jkgwService.updateJkgw(jkgw);

        String message = String.format("更新杆件：　杆件id=%d,　杆件名称=%s", jkgw.getGw_id(), jkgw.getGw_name());
        String opCondition = String.format("gw_id=%s", gw_id);
        asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_UPDATE, Constants.UPDATE, opCondition, message);
    }


    @PostMapping("detail/{id}")
    public JkgwVO jkgwDetail(@PathVariable("id") Integer gw_id) {

        Jkgw jkgw = jkgwService.getById(gw_id);
        log.info("jkgw.getGw_jd============="+jkgw.getGw_jd()+"  "+jkgw.getGw_wd());

        Double radius=null;
        Double rds = jkgw.getGw_search_radius();
        if (rds==0.0){
            radius=Constants.COMMON_RADIUS;
        }else {
            radius=jkgw.getGw_search_radius();
        }
        //根据杆件经纬度查询附近设备列表
//        List<Qdsxj> qdsxjList = qdsxjService.getEquipmentList(jkgw.getGw_jd(),jkgw.getGw_wd(),radius);
        List<Qdsxj> qdsxjList = qdsxjService.getListByGwId(gw_id);
        // 选中复选框list
        List<Integer> checkList = new ArrayList<>();
        for (Qdsxj qdsxj:qdsxjList) {
            log.info("摄像机ID：==========================="+qdsxj.getSb_id());
            log.info("摄像机名称：=========================="+qdsxj.getSb_name());
            //从关联表查询设备id
            List<Equipmen> sbids = equipmenService.getGwIdList();

            for (int i = 0; i <sbids.size() ; i++) {
                //如果有将设备选中状态改变
                if (sbids.get(i).getSb_id().equals(qdsxj.getSb_id())){
                    qdsxj.setChecked(true);
                    checkList.add(qdsxj.getSb_id());
                }
            }
        }
        log.info("checkList:===================="+checkList);

        JkgwVO vo = new JkgwVO();
        BeanUtils.copyProperties(jkgw, vo);
        vo.setQdsxjList(qdsxjList);
        vo.setCheckList(checkList);

        String message = String.format("查看杆件绑定：　杆件id=%d,　杆件名称=%s", jkgw.getGw_id(), jkgw.getGw_name());
        String opCondition = String.format("gw_id=%d", gw_id);
        asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_QUERY, Constants.UPDATE, opCondition, message);

        return vo;
    }

    @GetMapping(value = "/bindSearch")
    @ResponseBody
    public List<Qdsxj> jkgwBindView2(Integer gw_id,Double radius){
        log.info("jkgwBindViewSearch:===================="+gw_id+" 半径："+radius);
        Jkgw jkgw = jkgwService.getById(gw_id);
        if(Objects.isNull(jkgw)){
            log.info("jkgw.getGw_jd============="+jkgw.getGw_jd()+"  "+jkgw.getGw_wd());
        }
        //根据杆件经纬度查询附近设备列表
        List<Qdsxj> qdsxjList = qdsxjService.getListByGwId(gw_id);
//        List<Qdsxj> qdsxjList = qdsxjService.getEquipmentList(jkgw.getGw_jd(),jkgw.getGw_wd(),radius);
        // 选中复选框list
        List<Integer> checkList = new ArrayList<>();
        for (Qdsxj qdsxj:qdsxjList) {
            log.info("摄像机ID：==========================="+qdsxj.getSb_id());
            log.info("摄像机名称：=========================="+qdsxj.getSb_name());
            //从关联表查询设备id
            List<Equipmen> sbids = equipmenService.getGwIdList();

            for (int i = 0; i <sbids.size() ; i++) {
                //如果有将设备选中状态改变
                if (sbids.get(i).getSb_id().equals(qdsxj.getSb_id())){
                    qdsxj.setChecked(true);
                }
            }
        }
        return qdsxjList;
    }

    @PostMapping(value = "/bind/{id}")
    @ResponseBody
    public JSONObject jkgwBind(@PathVariable("id") Integer gw_id,
                               @RequestParam(name = "sbList")String sbList){
        System.err.println("gw_id----------------"+gw_id);
        System.err.println("sbList----------------"+sbList);
        JSONObject json =new JSONObject();
        RzLog rzLog = new RzLog();
        //设备id数组
        String[] sb_ids = sbList.split(",");

        //根据杆位ID查询设备ID
        List<Integer> sblist = equipmenService.findByGwID(gw_id);

        //传入半径修改杆件半径
        log.info("杆件id:====================="+sblist);
       // jkgwService.updateJkgwRadius(gw_id);
        if (!sblist.isEmpty()){
            //根据杆位ID删除
            int num = equipmenService.deleteByGwid(gw_id);
            System.out.println("后台删除 sblist ："+num);
        }
        Jkgw jkgw = jkgwService.getById(gw_id);
        String qr_bm=jkgw.getGw_bm();
        if(StringUtils.isEmpty(qr_bm)){
            json.put("error","监控杆位编码不存在");
            json.put("code",400);
        }
        System.err.println(qr_bm);
        QRCode qrCode = qrCodeService.getByQrBm(qr_bm);
        Integer qrId = 0;
        if(Objects.nonNull(qrCode)) {
            qrId = qrCode.getQr_id();
        }
        for (int i = 0; i <sb_ids.length ; i++) {
            //绑定插入操作
            equipmenService.insertSbBind(qrId,gw_id,Integer.parseInt(sb_ids[i]));
        }
        String message = String.format("更新杆件绑定：　杆件id=%d,　杆件名称=%s", jkgw.getGw_id(), jkgw.getGw_name());
        String opCondition = String.format("gw_id=%d", gw_id);
        asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_UPDATE, Constants.UPDATE, opCondition, message);

        json.put("code",200);
        return  json;
    }
}
